﻿using System;
using System.Collections.Generic;
using System.Linq;
using LDM.Sys.Repository.Interfaces;
using LDM.Sys.ServiceAPI.Model.DBModel;
using LDM.Sys.ServiceAPI.Model.Enum;
using LDM.Sys.ServiceAPI.Model.ViewModel.Response.Authority;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model.Enum.ConfigModel;
using SqlSugar;
using Utility.Datas.Queries;
using Utility.DB.SqlSugar;
using Utility.Extensions;

namespace LDM.Sys.Repository.Repository
{
    /// <summary>
    /// 用户权限资源关联仓储
    /// </summary>
    public class SysRoleAuthorityRelRepository : DbContextBase<SysRoleAuthorityRel>, ISysRoleAuthorityRelRepository, IScoped
    {
        public SysRoleAuthorityRelRepository(IConfiguration configuration) :
           base(configuration.GetConnectionString(ConnectionStringType.UserMysql.GetDescription()))
        {



        }


        /// <summary>
        /// 获取角色权限资源项
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public List<SysRoleAuthorityRel> GetAuthorityByRoleIds(IEnumerable<int> roleIds)
        {
            return Db.Queryable<SysRoleAuthorityRel>().Where(x => roleIds.Contains(x.RoleId)).ToList();
        }

        /// <summary>
        /// 获取指定类型权限资源项的
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public List<SysRoleAuthorityRel> GetAuthorityByAuthorityIds(IEnumerable<int> authorityIds, AuthorityTypeEnum authorityType)
        {
            return Db.Queryable<SysRoleAuthorityRel>().Where(x => authorityIds.Contains(x.AuthorityId) && x.AuthorityType == (int)authorityType).ToList();
        }

        /// <summary>
        /// 根据角色获取用户ID获取菜单
        /// </summary>
        public IEnumerable<AuthorityMenuRes> GetuthorityMenuByRoleIds(IEnumerable<int> roleIds)
        {
            return Db.Queryable<SysRoleAuthorityRel>()
              .LeftJoin<SysMenu>((ra, m) => ra.AuthorityId == m.Id)
              .Where((ra, m) => roleIds.Contains(ra.RoleId) && ra.AuthorityType == (int)AuthorityTypeEnum.Menu)
              .Select((ra, m) => new AuthorityMenuRes()
              {
                  RoleId = ra.RoleId,
                  MenuId = ra.AuthorityId,
                  MenuName =m.MenuName,
                  MenuType = m.MenuType,
                  Icon = m.Icon,
                  PMenuId = m.PId,
                  Url = m.Url,
              }).ToList();
        }

    }
}